package com.shigu.annotations.aspects;

import com.alibaba.fastjson.JSONObject;
import com.opentae.data.mall.beans.ManagerUser;
import com.opentae.data.mall.beans.ManagerUserRecord;
import com.opentae.data.mall.interfaces.ManagerUserRecordMapper;
import com.shigu.annotations.UserOption;
import com.shigu.component.enums.SessionEnum;
import com.shigu.component.shiro.AuthorityUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Aspect //该注解标示该类为切面类
@Component //注入依赖
public class UserOptionAspect {

    @Autowired
    ManagerUserRecordMapper managerUserRecordMapper;

    //标注该方法体为后置通知，当目标方法执行成功后执行该方法体
    @Before("within(com.shigu..*) && @annotation(rl)")
    public void addLogSuccess(JoinPoint jp, UserOption rl){
        ManagerUserRecord record=new ManagerUserRecord();
        record.setFunctionName(rl.function());
        record.setActiveTime(new Date());
        Object[] parames = jp.getArgs();//取出参数
        List<Object> paramList=new ArrayList<>();
        for(Object param:parames){//request   bindResult model session不要
            if (param instanceof HttpServletRequest ||param instanceof BindingResult
                    ||param instanceof Model ||param instanceof HttpSession||param instanceof MultipartFile) {
                continue;
            }
            paramList.add(param);
        }
        record.setParamContent(JSONObject.toJSONString(paramList));
        record.setActiveIp("0.0.0.0");
        try {
            AuthorityUser user= (AuthorityUser) SecurityUtils.getSubject().getSession().getAttribute(SessionEnum.LOGIN_USER.toString());
            if (user != null) {
                record.setUserId(user.getUserId());
                record.setUserName(user.getUserName());
            }
        } catch (Exception e) {
            //取不到是正常现象
        }
        managerUserRecordMapper.insertSelective(record);
    }
}
